package com.pengchuang.ACS.face.controller;

import com.pengchuang.ACS.common.constant.GlobalConstants;
import com.pengchuang.ACS.common.utils.R;
import com.pengchuang.ACS.common.utils.ResultCode;
import com.pengchuang.ACS.face.entity.FileEntity;
import com.pengchuang.ACS.face.service.FileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @projectName: AccessControlSystem
 * @see: com.pengchuang.ACS.face.controller
 * @author: pc
 * @createTime: 2023/3/16 15:24
 * @version: 1.0
 */
@RequestMapping("/file")
@Slf4j
@AllArgsConstructor
@RestController
public class FileController {

	// 这里以后换成字典进行存储 TODO
	public static double uploadImageSize = 2;
	public static String[] uploadImageTypes = new String[]{"image/jpeg", "image/png"};

	private final FileService fileService;

	@PostMapping("/upload")
	public R uploadImage(@RequestParam MultipartFile multipartFile) {

		if (multipartFile.isEmpty()) {
			return R.error(ResultCode.PICTURE_ERROR);
		}

		//检查格式
		String fileType = multipartFile.getContentType();
		boolean flag = false;
		for (String type : uploadImageTypes) {
			if (type.equals(fileType)) {
				flag = true;
				break;
			}
		}
		if (!flag) {
			return R.error(ResultCode.PICTURE_ERROR_TYPE);
		}

		//检查文件大小
		double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
		NumberFormat nf = new DecimalFormat("0.00");
		if (imageSize > uploadImageSize) {
			return R.error(ResultCode.PICTURE_ERROR_SIZE);
		}

		String fileName = multipartFile.getOriginalFilename();//文件名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀名
		fileName = UUID.randomUUID() + suffixName;//图片名
		// 本地缓存图片
		String imagePath = GlobalConstants.TEMP_FILEPATH + "/" + fileName;//图片的url
		File dest = new File(imagePath);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}

		try {
			multipartFile.transferTo(dest);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result", GlobalConstants.URL_PATH + fileName);
			return R.ok(map);
		} catch (IOException ignored) {
			return R.error();
		}

	}

	@GetMapping("/getStore/{imageName}")
	@ResponseBody
	public R storeImage(@RequestParam Long userId, @PathVariable String imageName) {
		// 进行路径转移
		File oldName = new File(GlobalConstants.TEMP_FILEPATH + imageName);

		if (!oldName.exists()) {
			return R.ok();
		}

		if (oldName.isDirectory()) {
			return R.error();
		}

		File newName = new File(GlobalConstants.FILEPATH + userId + "/" + imageName);
		if (!newName.getParentFile().exists()) {
			newName.getParentFile().mkdirs();
		}

		if (newName.isDirectory()) {
			return R.error();
		}

		if (oldName.renameTo(newName)) {
			// 持久化层进行记录操作
			String suffixName = imageName.substring(imageName.lastIndexOf("."));//后缀名
			fileService.save(FileEntity.builder()
							.filePath(GlobalConstants.FILEPATH + userId + "/" + imageName)
							.fileType(suffixName)
							.fileName(imageName)
							.status(1)
							.build());

			return R.ok();
		}
		return R.error();
	}

	@GetMapping("/get/{imageName}")
	@ResponseBody
	public void getImage(@RequestParam(required = false) Long userId, @PathVariable String imageName, HttpServletResponse response) {
		if (userId == null && imageName == null) {
			return;
		}
		File file = new File( GlobalConstants.TEMP_FILEPATH + imageName + ".jpg");
		if (!file.exists()) {
			file = new File( GlobalConstants.FILEPATH + userId + "/" + imageName + ".jpg");
		}
		if (!file.exists()) return;
		FileInputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(file);
			int i = in.available();
			byte[] buffer = new byte[i];
			in.read(buffer);
			//设置输出流内容格式为图片格式
			response.setContentType("image/jpeg");
			//response的响应的编码方式为utf-8
			response.setCharacterEncoding("utf-8");
			out = response.getOutputStream();
			out.write(buffer);
		} catch (Exception e) {

		} finally {
			try {
				in.close();
				out.close();
			} catch (IOException e) {

			}
		}
	}

}
